const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()
const port = 30000

const handlebars = require('handlebars')
const fs = require('fs')
const stream = require('stream')
let template

app.use(cors())
app.use(bodyParser())

const context = '/generator'
const outputDir = 'output'
const fileSuffix = '.vue'

const routeTable = '/data-table'

const getFileName = (route) => outputDir + route + fileSuffix


app.post(context + routeTable, (req, res) => {
	let fileName = getFileName(routeTable)
	let data = req.body
  let fileContents

	fs.writeFile(fileName, template({tableConfig: JSON.stringify(data), pageName: data.pageName}), (err) => {
		if (err) throw err;
		console.log(fileName + ' has been generated!');
	})
  res.sendStatus(200)
})

app.get(context + routeTable, (req, res) => {
	res.download(getFileName(routeTable))
})

// readFile返回默认是buffer
fs.readFile('data-table.vue', 'utf8', (err, data) => {
  if (err) throw err;
	template = handlebars.compile(data)
  console.log('has readed data-table template');

	app.listen(port, () => console.log(`generator app listening on port ${port}!`))
})

